<template>
    <div class="content-preview">
        <template v-if="typeof content === 'string' && isJsonString(content)">
            <div v-for="(item, index) in parseContentJson(content)" :key="index" class="content-item">
                <template v-if="item.type === 'text'">
                    <div class="text-content">{{ item.content }}</div>
                </template>
                <template v-else-if="item.type === 'image' && item.content">
                    <ImagePreview :src="item.content" width="80px" height="80px" />
                </template>
            </div>
        </template>
        <template v-else>
            {{ content }}
        </template>
    </div>
</template>

<script setup lang="ts">
import ImagePreview from '@/components/ImagePreview/index.vue'

interface Props {
    content: string | any
}

const props = defineProps<Props>()

// 判断字符串是否为有效的JSON格式
const isJsonString = (str: string): boolean => {
    try {
        JSON.parse(str)
        return true
    } catch (e) {
        return false
    }
}

// 解析内容JSON字符串为图文混合内容数组
const parseContentJson = (jsonStr: string) => {
    try {
        const parsed = JSON.parse(jsonStr)
        if (Array.isArray(parsed) && parsed.length > 0) {
            return parsed
        } else {
            // 如果解析结果不是数组或为空，则创建一个默认文本项
            return [{ content: jsonStr || '', type: 'text' }]
        }
    } catch (error) {
        // 如果解析失败，将原始字符串作为文本内容
        return [{ content: jsonStr || '', type: 'text' }]
    }
}
</script>

<style scoped>
.content-preview {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.content-item {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.text-content {
    word-break: break-word;
    line-height: 1.4;
}
</style>